package models

import (
	"gintest/database"
	"time"
)
//表结构
type User struct {
	Id        int        `json:"id" gorm:"column:id;primary_key" form:"id"`
	UserName  string     `json:"username" gorm:"column:username" form:"username"`
	PassWord  string     `json:"password" gorm:"column:password" form:"password"`
	Phone     string	 `json:"phone" gorm:"column:phone" form:"phone"`
	NickName  string	 `json:"nickname" gorm:"column:nickname" form:"nickname"`
	Email     string     `json:"email" gorm:"column:email" form:"email"`
	Avatar    string     `json:"avatar" gorm:"column:avatar" form:"avatar"`
	Sex       int        `json:"sex" gorm:"column:sex" form:"sex"`
	CreateAt  time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	DeleteAt time.Time  `json:"delete_at" gorm:"column:delete_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"delete_at"`

	UserThird []UserThird `json:"userthird" gorm:"ForeignKey:UserId;AssociationForeignKey:Id"`
}
func (User) TableName() string {
	return "users"
}
//得到记录列表
func GetUserList(page uint64,pagesize uint64,keyword string) (data []User,total uint64) {
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(User{})

	if len(keyword)!=0{
		db=db.Where("concat(username,email,phone,nickname) like ?","%"+keyword+"%")
	}

	db=db.Where("delete_at = 0 or delete_at is null")

	db.Offset(offset).Limit(pagesize).Order("create_at desc").Preload("UserThird").Find(&data)
	//db.Select("users.*").Joins("left JOIN sl_group_user ON sl_group_user.user_id = sl_user.id").Where("sl_group_user.group_id=?",5).Preload("UserAuth").Offset(offset).Limit(pagesize).Order("create_time desc").Find(&data)

	db.Model(User{}).Count(&total)

	return
}
func AddUser(data *User) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	db:=database.SqlDB.Model(User{})
	if len(data.UserThird)<=0{
		db=db.Omit("UserThird")
	}
	return db.Create(data).Error
}
func DelUserByIds(ids []int) error{
	//return database.SqlDB.Model(User{}).Where("id in (?)",ids).Delete(User{}).Error
	tx:=database.SqlDB.Begin()
	err:=tx.Model(Delivery{}).Where("user_id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
	if err!=nil{
		tx.Rollback()
		return err
	}
	err=tx.Model(User{}).Where("id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
	if err!=nil{
		tx.Rollback()
	}
	tx.Commit()
	return nil
}
func GetUserById(id int) (data User){
	database.SqlDB.Model(User{}).Where("id=?",id).First(&data);
	return data
}
func GetUserByPhone(phone string)(data User){
	database.SqlDB.Model(User{}).Where("phone=?",phone).First(&data);
	return data
}
func EditUserById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	return database.SqlDB.Model(&User{}).Where("id=?",id).Updates(data).Error
}
func GetUserCount() (total int){
	database.SqlDB.Table("users").Where("delete_at = 0 or delete_at is null").Count(&total)
	return
}

//验证手机号唯一性
func UniqueUserPhone(not_id uint64,code string)(total int){
	return baseUserUnique(not_id,"phone",code)
}
//验证用户名唯一性
func UniqueUserUserName(not_id uint64,username string)(total int){
	return baseUserUnique(not_id,"username",username)
}
//字段唯一验证
func baseUserUnique(not_id uint64,fd_name,val string)(total int){
	db:=database.SqlDB.Model(User{})
	if not_id!=0{
		db=db.Where("id !=?",not_id)
	}
	sql:="(delete_at = 0 or delete_at is null) and (" + fd_name + " = ?)"
	db.Where(sql,val).Count(&total)
	return
}
func GetUserByOpenId(openid string)(data User){
	database.SqlDB.Model(User{}).Select("users.*").Joins("left join users_third on users_third.user_id=users.id").Where("users_third.third_key=?",openid).First(&data);
	return data
}
